package com.alibaba.yygh.oss.service.impl;

import com.alibaba.yygh.oss.service.FileService;
import com.alibaba.yygh.oss.utils.ConstantOssPropertiesUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * description: FileServiceImpl
 * @author: gql
 * @date: 2021/11
 */
@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file) {
        // 1.获取上传需要的几个值
        String endpoint = ConstantOssPropertiesUtils.END_POINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantOssPropertiesUtils.BUCKET_NAME;
        try {
            // 2.创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 3.获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            // 3.1获取文件名
            String fileName = file.getOriginalFilename();
            // 3.1文件名添加随机值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;
            // 3.2文件名按日期创建文件夹分类
            String dateUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = dateUrl + "/" + fileName;

            /**
             * 6.调用方法实现上传
             * args1: bucketName
             * args2: 上传的文件的路径和名称
             * args3:
             */
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient
            ossClient.shutdown();

            // 8.上传文件在阿里云的路径
            // https://yygh-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
